package com.lws.basic.model;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;


/**
 * @松 on 2019/9/9 12:56
 */
public class OkHttpUtils {
    private static OkHttpClient okHttpClient;

    private static OkHttpClient getInstance() {
        if (okHttpClient == null) {
            synchronized (OkHttpUtils.class) {
                if (okHttpClient == null) {
                   HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
                   // 设置日志打印级别
                    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(10, TimeUnit.SECONDS)//10秒连接超时
                            .writeTimeout(10, TimeUnit.SECONDS)//10m秒写入超时
                            .readTimeout(10, TimeUnit.SECONDS)//10秒读取超时
                            .addNetworkInterceptor(loggingInterceptor)
                            .build();
                }
            }
        }
        return okHttpClient;
    }

    public static String post(String json, String url) throws IOException {
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = getInstance().newCall(request).execute();
        return response.body().string();
    }

    public static String get( String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = getInstance().newCall(request).execute();
        return response.body().string();
    }

    public static String uploadImage( String url ,File file) throws IOException {
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("files", file.getName(), fileBody)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = getInstance().newCall(request).execute();
        return response.body().string();
    }
}
